package com.quktzhuanka.app.fragments;


import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.quktzhuanka.app.R;
import com.quktzhuanka.app.activity.PddDetailsActivity;
import com.quktzhuanka.app.adapter.PddRecyclerAdapter;
import com.quktzhuanka.app.base.BaseLazyFragment;
import com.quktzhuanka.app.bean.PDDBean;
import com.quktzhuanka.app.bean.PddClient;
import com.quktzhuanka.app.common.SPUtils;
import com.quktzhuanka.app.https.HttpUtils;
import com.quktzhuanka.app.utils.DrawableCenterTextView;
import com.quktzhuanka.app.utils.UIUtils;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cz.msebera.android.httpclient.Header;

/**
 * @属性:拼多多商品页
 * @开发者:wmm
 * @时间:2018/11/21 17:36
 */
public class PddFragment extends BaseLazyFragment{


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    Unbinder unbinder;


    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.right_icon)
    ImageView rightIcon;
    private PddRecyclerAdapter shopRecyclerAdapter;
    private String pid;

    List<PDDBean> taobaoGuesChildtBeans = new ArrayList<>();
    private int indexNum = 1;
    private String name;
    private String sort;
    private LinearLayoutManager linearLayoutManager;
    private boolean hasdata=true;
    private String sort_gz="0";
    Gson gson=new Gson();
    DecimalFormat df=new DecimalFormat("0.00");
    private TextView[] textViews;
    @BindView(R.id.jiage_st)
    DrawableCenterTextView jiageSt;
    @BindView(R.id.xiaoliang_st)
    DrawableCenterTextView xiaoliangSt;
    @BindView(R.id.yongjin_st)
    DrawableCenterTextView yongjinSt;
    @BindView(R.id.tuiguang_st)
    DrawableCenterTextView tuiguangSt;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pdd, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        addListener();
        return view;
    }

    private void init() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            pid = arguments.getString("pid");
            name = arguments.getString("name");
            sort = arguments.getString("sort");
        }
        tuiguangSt.setVisibility(View.GONE);
        yongjinSt.setText("奖");
        textViews = new TextView[]{jiageSt, xiaoliangSt, yongjinSt};
        shopRecyclerAdapter = new PddRecyclerAdapter(getActivity(), R.layout.pdd_item, taobaoGuesChildtBeans);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
//        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(shopRecyclerAdapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int screenMeasuredHeight = UIUtils.getScreenMeasuredHeight(getActivity());
                if (getScollYDistance() >= (screenMeasuredHeight / 2)) {
                    rightIcon.setVisibility(View.VISIBLE);
                } else {
                    rightIcon.setVisibility(View.GONE);
                }
            }
        });
    }

    private void addListener() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (hasdata) {
                    indexNum++;
                    getTbkListRequst(name);
                } else {
                    showToast("没有更多数据了");
                    refreshLayout.finishLoadMore(1000);
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                indexNum = 1;
                hasdata=true;
                getTbkListRequst(name);
            }
        });
        //点击进入详情
        shopRecyclerAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                PDDBean taobaoGuesChildtBean = taobaoGuesChildtBeans.get(position);
                if (taobaoGuesChildtBean != null) {
                    Intent intent=new Intent(context,PddDetailsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("goods", taobaoGuesChildtBean);
                    intent.putExtra("goods",bundle);
                    startActivity(intent);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    /**
     * @属性:获取屏幕高度的方法
     * @开发者:田哥哥
     * @时间:2018/8/7 14:22
     */
    public long getScollYDistance() {
        int position = linearLayoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = linearLayoutManager.findViewByPosition(position);
        int itemHeight = firstVisiableChildView.getHeight();
        return (position) * itemHeight - firstVisiableChildView.getTop();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void lazyload() { //懒加载，界面开始后刷新
        //开始刷新
        refreshLayout.autoRefresh();
    }
    /**
     * @属性:获取Pdd商品列表
     * @开发者:wmm
     * @时间:2018/11/21 17:05
     */
    private void getTbkListRequst(String search) {
        String time=String.valueOf(System.currentTimeMillis() / 1000);
        RequestParams requestParams = new RequestParams();
        requestParams.put("page",indexNum+"");
        requestParams.put("sort_type",sort_gz);
        requestParams.put("page_size","10");
        requestParams.put("data_type",PddClient.data_type);
        requestParams.put("client_id",PddClient.client_id);
        requestParams.put("timestamp",time);
        requestParams.put("with_coupon","true");
        requestParams.put("type","pdd.ddk.goods.search");
        if(pid.equals("0")){
            requestParams.put("opt_id",pid);
        }else{
            requestParams.put("cat_id", pid);
        }
        Map<String,Object> temp=new HashMap<>();
        temp.put("page",indexNum+"");
        if(pid.equals("0")){
            temp.put("opt_id",pid);
        }else{
            temp.put("cat_id", pid);
        }
        temp.put("sort_type",sort_gz);
        temp.put("page_size","10");
        temp.put("data_type",PddClient.data_type);
        temp.put("type","pdd.ddk.goods.search");
        temp.put("client_id",PddClient.client_id);
        temp.put("timestamp",time);
        temp.put("with_coupon","true");
        String sign=PddClient.getSign(temp);
        requestParams.put("sign",sign);
        HttpUtils.post1(PddClient.serverUrl, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
                if (refreshLayout != null) {
                    if (indexNum == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if(responseString.contains("error_response")){
                    return;
                }
                if(indexNum==1){
                    taobaoGuesChildtBeans.clear();
                }
                try {
                    JSONObject jsonObject=new JSONObject(responseString);
                    JSONArray array=jsonObject.getJSONObject("goods_search_response").getJSONArray("goods_list");
                    JSONObject tempObj;
                    for(int i=0;i<array.length();i++){
                        tempObj=array.getJSONObject(i);
                        double tem=(Double.valueOf(tempObj.getString("min_group_price"))-Double.valueOf(tempObj.getString("coupon_discount")))*Double.valueOf(df.format(Double.valueOf(tempObj.getString("promotion_rate"))/1000));
                        tempObj.put("commission",df.format(  tem*SPUtils.getIntData(context,"rate",0)/100));
                        taobaoGuesChildtBeans.add(gson.fromJson(tempObj.toString(),PDDBean.class));
                    }
                    shopRecyclerAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick({R.id.right_icon,R.id.jiage_st,R.id.yongjin_st,R.id.xiaoliang_st})
    public void onViewClicked(View view) { //回到头部
        switch (view.getId()) {
            case R.id.right_icon:
                recyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        recyclerView.smoothScrollToPosition(0);
                    }
                });
                break;
            case R.id.xiaoliang_st: //销量
                if ("6".equals(sort_gz)) {
                    sort_gz = "5";
                    Drawable nav_bo=getResources().getDrawable(R.mipmap.sort_select);
                    nav_bo.setBounds(0, 0, nav_bo.getMinimumWidth(), nav_bo.getMinimumHeight());
                    xiaoliangSt.setCompoundDrawables(null, null, nav_bo, null);
                } else {
                    sort_gz = "6";
                    Drawable nav_up=getResources().getDrawable(R.mipmap.sort_normal);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                    xiaoliangSt.setCompoundDrawables(null, null, nav_up, null);
                }
                refreshLayout.autoRefresh();
                selectView(1);
                break;
            case R.id.jiage_st: //价格
                if ("4".equals(sort_gz)) {
                    sort_gz = "3";
                    Drawable nav_bo=getResources().getDrawable(R.mipmap.sort_select);
                    nav_bo.setBounds(0, 0, nav_bo.getMinimumWidth(), nav_bo.getMinimumHeight());
                    jiageSt.setCompoundDrawables(null, null, nav_bo, null);
                } else {
                    sort_gz = "4";
                    Drawable nav_up=getResources().getDrawable(R.mipmap.sort_normal);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                    jiageSt.setCompoundDrawables(null, null, nav_up, null);
                }
                selectView(0);
                refreshLayout.autoRefresh();
                break;
            case R.id.yongjin_st: //奖
                if ("14".equals(sort_gz)) {
                    sort_gz = "13";
                    Drawable nav_bo=getResources().getDrawable(R.mipmap.sort_select);
                    nav_bo.setBounds(0, 0, nav_bo.getMinimumWidth(), nav_bo.getMinimumHeight());
                    yongjinSt.setCompoundDrawables(null, null, nav_bo, null);
                } else {
                    sort_gz = "14";
                    Drawable nav_up=getResources().getDrawable(R.mipmap.sort_normal);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                    yongjinSt.setCompoundDrawables(null, null, nav_up, null);
                }
                refreshLayout.autoRefresh();
                selectView(2);
                break;
        }
    }
    private void selectView(int position) {
        for (TextView textView : textViews) {
            textView.setTextColor(getResources().getColor(R.color.black));
        }
        textViews[position].setTextColor(getResources().getColor(R.color.gold));
    }

}
